// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#include <pollux/expression/eval_ctx.h>
#include <pollux/expression/vector_function.h>

namespace kumo::pollux::functions::lib {
    // Sort on an indices array by corresponding values array
    template<typename T>
    struct Index2ValueNullableLess {
        explicit Index2ValueNullableLess(
            const exec::LocalDecodedVector &decodedVector)
            : decodedVector_(decodedVector) {
        }

        constexpr bool operator()(const vector_size_t &a, const vector_size_t &b)
        const {
            // null should be moved to the head of the array
            if (decodedVector_->is_null_at(a)) {
                return !decodedVector_->is_null_at(b);
            }
            if (decodedVector_->is_null_at(b)) {
                return false;
            }
            return decodedVector_->value_at<T>(a) < decodedVector_->value_at<T>(b);
        }

    private:
        const exec::LocalDecodedVector &decodedVector_;
    };

    template<typename T>
    struct Index2ValueNullableGreater : private Index2ValueNullableLess<T> {
        constexpr bool operator()(const vector_size_t &a, const vector_size_t &b)
        const {
            return Index2ValueNullableGreater<T>::operator()(b, a);
        }
    };
} // namespace kumo::pollux::functions::lib
